<template>
  <div class="app-container jklis">
    <div class="zdy-main">
      <div style="margin-bottom: 10px;">
        <subtit title="系统推广"></subtit>
        <div v-if="tuiguangCode&&tuiguangCode.referralCode" style="margin: 10px 0;">
          我的推广链接：
          <span class="mylink" style="margin-right: 10px;">{{ tuiguangLink }}</span>
          <el-button size="mini" type="primary" plain @click="copyStr(tuiguangLink)">复制</el-button>
          <el-button size="mini" type="primary" @click="openQRCode">生成海报</el-button>

          <!-- <span class="font16 " style="margin-left: 20px;">
            总计返佣：
            <b style="color: red;">
              <span class="font24" >{{ totalAmount.linksPriceRebateSum||'--' }}</span>
              元
            </b>
          </span> -->
        </div>
      </div>
      <div class="tongji">
        <div class="tit" style="margin: 10px;">
          <span style="width: 0px;height: 12px;border: 1px solid #6C5DD3;margin-right: 6px;"></span>
          <span style="font-size: 16px;font-weight: 500;">推广返现</span>
        </div>
        <div class="tongji_box flex">
          <div>
            <b>当前已邀请注册</b>
            <div class="val">
              <span>{{  this.tableData.total||'--'}}</span>
              人
            </div>
          </div>
          <div>
            <b>总计返佣</b>
            <div class="val">
              <span style="color: #EB8200;">{{ totalAmount.linksPriceRebateSum||'--' }}</span>
              元
            </div>
          </div>
        </div>
      </div>
      <div class="tongji">
        <div class="tit" style="margin: 10px; ">
          <span style="width: 0px;height: 12px;border: 1px solid #6C5DD3;margin-right: 6px;"></span>
          <span style="font-size: 16px;font-weight: 500;">推广经验</span>
        </div>
        <div class="tuiguangjjingyan flex">
          <img src="https://imgage.maimaihao.com/yuduhulian/erp/static/img/tuiguangjingyan01.png" alt="">
          <img src="https://imgage.maimaihao.com/yuduhulian/erp/static/img/tuiguangjingyan02.png" alt="">
          <img src="https://imgage.maimaihao.com/yuduhulian/erp/static/img/tuiguangjingyan03.png" alt="">
          <img src="https://imgage.maimaihao.com/yuduhulian/erp/static/img/tuiguangjingyan04.png" alt="">
          <img src="https://imgage.maimaihao.com/yuduhulian/erp/static/img/tuiguangjingyan05.png" alt="">
        </div>
      </div>
      <!-- <div style="height:40px;line-height: 40px;background-color: antiquewhite;border-radius: 8px;padding: 0 20px;font-size: 16px;margin-bottom: 10px;">
        您推广的商户
      </div> -->
      <!-- <div style="height: 15px;border-top: 1px solid #eee;"></div> -->
      <div class="content">
        <div class="tit" style="margin: 10px;">
          <span style="width: 0px;height: 12px;border: 1px solid #6C5DD3;margin-right: 6px;"></span>
          <span style="font-size: 16px;font-weight: 500;">推广明细</span>
        </div>
        <el-form ref="queryForm" :inline="true" class="zdy-form search-form-new" label-width="68px">
          <!-- <el-form-item label="店铺" prop="tenantId" v-hasPermi="['searchTenantID']">
          <el-select v-model="queryParams.tenantId" placeholder="请选择店铺" clearable filterable>
            <el-option v-for="dict in tenantList" :key="dict.tenantId" :label="dict.tenantName" :value="dict.tenantId" />
          </el-select>
        </el-form-item> -->

          <el-form-item label="注册时间">
            <el-date-picker clearable v-model="timerange2" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
          <el-form-item class="btns">
            <el-button type="primary" icon="el-icon-search" @click="searchFn">搜索</el-button>
            <el-button type="warning" icon="el-icon-refresh" @click="resetQuery">重置</el-button>

          </el-form-item>
        </el-form>
        <div class="table_box" v-loading="loading">
          <el-table :data="tableData.records" border>

            <el-table-column label="店铺名称" prop="contractName">
              <template slot-scope="scope">
                <span>{{ getRegisterInfo(scope.row.registerInfo).tenantName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="注册时间" prop="finishTime" />
            <el-table-column label="开户费" prop="linksPrice"> </el-table-column>
            <el-table-column label="返佣" prop="linksPriceRebate"> </el-table-column>
            <!-- <el-table-column label="创建人" prop="createName"> </el-table-column> -->

            <!-- <el-table-column label="状态" prop="payStatus" width="100">
            <template slot-scope="scope">
              <div>
                <el-tag type="success" v-if="scope.row.payStatus==2">已支付</el-tag>
                <el-tag type="warning" v-else>未支付</el-tag>

              </div>
            </template>
          </el-table-column> -->

            <!-- <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button v-if="scope.row.status==2" type="text" @click="downloadFile(scope.row)">下载合同</el-button>
              <el-button type="text" @click="openView(scope.row)">签署详情</el-button>
              <el-button v-if="scope.row.status==1&&checkPermi(['chexiaohetong'])" type="del" @click="cancelContract(scope.row)">撤销合同</el-button>
            </template>
          </el-table-column> -->
          </el-table>
        </div>

        <div class="pages-box">
          <pagination v-show="tableData.total>0" :total="tableData.total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

        </div>
      </div>

    </div>
    <!-- <el-dialog title="我的推广码" :visible.sync="qrCodeShow" width="620px">
      <div style="width:260px; height:260px;background-color: #fff;margin:0 auto;margin-bottom:15px;padding: 10px;border-radius: 5px;box-shadow: 0 4px 16px 0 rgba(0,0,0,.1);">
        <div class="qrcodeDom" ref="qrcode" style="width:240px; height:240px;margin:0 auto;"></div>
      </div>

      <div style="margin-top: 15px;">
        <div style="text-align: center;">
          <span class="mylink"> <a :href="tuiguangLink" target="_blank">{{tuiguangLink}}</a></span>
          <el-button size="mini" @click="copyStr(tuiguangLink)">复制</el-button>
        </div>
      </div>
    </el-dialog> -->
    <haibaoDialog ref="haibaoDialog"></haibaoDialog>
  </div>
</template>

<script>
import fadadaApi from "../../api/B2Cmanage/fadada";
import tuiguangApi from "../../api/tuiguang/tuiguang";

import subtit from "@/components/indexComponents/subtit.vue";
import haibaoDialog from "./haibaoDialog.vue";
export default {
  name: "Tuiguang",
  components: {
    subtit,
    haibaoDialog
  },
  data() {
    return {
      timerange: [],
      timerange2: [],
      tableData: {
        records: [],
        total: 0,
      },
      queryParams: {
        pageSize: 10,
        pageNum: 1,
        payStatus: 2,
      },

      loading: false,

      guanwangDomain: "https://yuduhulian.com",
      tuiguangCode: "",
      tuiguangLink: "",
      qrCodeShow: false,
      qrcode: null,
      qrcodeImg: "",
      totalAmount: {},
    };
  },
  created() {
    this.getTuiguangCode();
    this.getList();
  },
  computed: {
    userInfo() {
      return this.$store.getters.userInfo;
    },
    shopInfo() {
      return this.$store.getters.shopInfo;
    },
    getRegisterInfo() {
      return (str) => {
        let obj = {};
        if (str) obj = JSON.parse(str);
        return obj;
      };
    },
  },
  methods: {
    // 查询推广链接
    getTuiguangCode() {
      tuiguangApi.getUserPromotionLinks().then((res) => {
        if (res.data && res.data.length) {
          this.tuiguangCode = res.data[0];
          this.tuiguangLink = `${this.guanwangDomain}/taocan?flag=${this.tuiguangCode.referralCode}`;
        } else {
          this.addTuiguangCode();
        }
      });
    },
    // 生成推广链接
    addTuiguangCode() {
      tuiguangApi.addUserPromotionLinks({}).then((res) => {
        this.getTuiguangCode();
      });
    },
    copyStr(txt) {
      this.$copyText(txt).then(() => {
        this.$message.success("已复制到剪切板");
      });
    },
    // 生成二维码
    openQRCode() {
      this.$refs.haibaoDialog.open(this.tuiguangLink)
      // this.qrCodeShow = true;

      // this.$nextTick(() => {
      //   const parentElement = document.getElementsByClassName("qrcodeDom");
      //   parentElement[0].innerHTML = "";
      //   if (this.qrcode != null) {
      //     this.qrcode.clear(); // 清除代码
      //   }
      //   this.qrcode = null;

      //   const width = 240;
      //   const height = 240;
      //   this.qrcode = new QRCode(this.$refs.qrcode, {
      //     text: this.tuiguangLink,
      //     width: width,
      //     height: height,
      //     correctLevel: QRCode.CorrectLevel.L,
      //     // colorDark: "#68b66b",
      //     colorDark: "#b640aa",
      //     colorLight: "#ffffff",
      //   });
      //   // 添加二维码中间的图片
      //   if (this.shopInfo.avatar) {
      //     let logo = new Image();
      //     logo.setAttribute("crossOrigin", "Anonymous");
      //     logo.src =
      //       "https://imgage.maimaihao.com/yuduhulian/logo1024x1024.jpg";
      //     logo.onload = () => {
      //       let qrDom = this.qrcode._el;
      //       let qrImg = this.qrcode._el.getElementsByTagName("img")[0];
      //       let canvas = this.qrcode._el.getElementsByTagName("canvas")[0];
      //       this.qrcode._el.title = "";
      //       canvas.style.display = "inline-block";
      //       let ctx = canvas.getContext("2d");
      //       // 设置logo的大小为二维码图片缩小的3.7倍，第二与第三参数代表logo在二维码的位置
      //       ctx.drawImage(
      //         logo,
      //         (width - width / 3.7) / 2,
      //         (height - height / 3.7) / 2,
      //         width / 3.7,
      //         height / 3.7
      //       );
      //       qrImg.src = canvas.toDataURL();
      //       qrImg.style.display = "none";
      //       // qrDom.removeChild(this.qrcode._el.getElementsByTagName("img"))
      //       // let parentNode = this.$refs.qrcode; // 获取参照元素的父元素
      //       // if (parentNode.contains(this.qrcode._el)) {
      //       //   parentNode.removeChild(this.qrcode._el); // 如果已存在于其他父元素中，先移除
      //       // }
      //       // this.$refs.qrcode.appendChild(this.qrcode._el);

      //       // this.qrcode.makeCode(this.tuiguangLink);
      //       clearTimeout(timer);
      //     };
      //   }
      //   // let timer = setTimeout(() => {

      //   // }, 100);

      //   //生成二维码
      //   // this.qrcode.makeCode(this.tuiguangLink);
      // });
    },

    // 获取列表
    getList() {
      this.tableData.records = [];
      this.loading = true;
      let obj = this.queryParams;
      // if (this.timerange.length == 2) {
      //   obj.createTimeStart = this.timerange[0] + " 00:00:00";
      //   obj.createTimeEnd = this.timerange[1] + " 23:59:59";
      // } else {
      //   obj.createTimeStart = "";
      //   obj.createTimeEnd = "";
      // }
      if (this.timerange2.length == 2) {
        obj.finishTimeStart = this.timerange2[0] + " 00:00:00";
        obj.finishTimeEnd = this.timerange2[1] + " 23:59:59";
      } else {
        obj.finishTimeStart = "";
        obj.finishTimeEnd = "";
      }
      tuiguangApi
        .userLinksOrderList(obj)
        .then((response) => {
          this.loading = false;
          this.totalAmount = { ...response.params };
          this.tableData.records = response.rows;
          this.tableData.total = response.total;
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    // 搜索
    searchFn() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置
    resetQuery() {
      this.queryParams = {
        pageSize: 10,
        pageNum: 1,
        payStatus: 2,
      };
      this.timerange2 = [];
      this.timerange = [];
      this.searchFn();
    },

    // 新增
    addACount() {
      this.$refs.CreateContract.open();
    },
    getUserTest() {
      fadadaApi
        .getuser({
          account: "yyenterprise13785552222",
          type: 2,
        })
        .then((res) => {});
    },
    //
    // shiming() {
    //   fadadaApi.testMobile3().then((res) => {
    //     if (res.msg) {
    //       const obj = JSON.parse(res.msg);
    //       this.serialNo = obj.serialNo;
    //     }
    //   });
    // },
    // jiaoyan() {
    //   fadadaApi
    //     .contractxiaoyan({
    //       captcha: this.yanzhengma,
    //       serialNo: this.serialNo,
    //     })
    //     .then((res) => {
    //       console.log("%c Line:122 🍔 res", "color:#f5ce50", res);
    //     });
    // },
    // 查看签署链接
    openView(row) {
      this.$refs.viewContract.open(row.id);
    },
    // 撤销合同
    cancelContract(row) {
      this.$confirm("合同撤销后不能继续签署，确定撤销该合同吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;

          // const authPhone= this.tabIndex==2?this.ruleForm.phone:this.ruleForm2.phone
          fadadaApi
            .contractcancel({
              id: row.id,
            })
            .then((res) => {
              if (res.code == 200) {
                this.$message.success("合同撤销成功！");
              }
              this.getList();
              this.loading = false;
            })
            .catch((err) => {
              this.loading = false;
            });
        })
        .catch(() => {});
    },
    isValidBase64(str) {
      // 使用正则表达式检查基本格式，并确保长度是4的倍数或可以通过填充补齐
      return (
        /^[A-Za-z0-9+/=]+$/.test(str) &&
        (str.length % 4 === 0 || str.match(/=+$/) !== null)
      );
    },
    // 查看
    downloadFile(row) {
      // 查看详情
      fadadaApi
        .getcontractIFile({
          id: row.id,
        })
        .then((res) => {
          const fileData = JSON.parse(res.msg);
          const base64Data = fileData.data.data;
          let mimeType = "application/pdf"; // 根据需要更改 MIME 类型
          if (fileData.data.fileType !== 0) {
            mimeType = "application/zip";
          }
          let fileType = ".pdf";
          if (fileData.data.fileType !== 0) {
            fileType = ".zip";
          }
          // 将 Base64 转换为二进制数据
          const byteCharacters = atob(base64Data);
          const byteNumbers = new Array(byteCharacters.length);
          for (let i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
          }
          const byteArray = new Uint8Array(byteNumbers);

          // 创建 Blob 对象
          const blob = new Blob([byteArray], { type: mimeType });

          // 创建下载链接
          const link = document.createElement("a");
          link.href = window.URL.createObjectURL(blob);
          link.download = row.contractName + fileType; // 下载的文件名

          // 触发下载
          link.click();

          // 释放 URL 对象
          window.URL.revokeObjectURL(link.href);
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.tongji {
  .tuiguangjjingyan{
    img{
      width: 152px;
      height: 158px;
      margin-right: 30px;
    }
  }
}
.tongji_box {
  width: 500px;
  height: 138px;
  background: rgba(228, 228, 228, 0.25);
  border-radius: 16px;
  border: 1px dashed #ccc;
  text-align: center;
  align-items: center;
  > div {
    width: 50%;
    b {
      font-size: 18px;
      color: #11142d;
    }
    .val {
      color: #999;
      margin-top: 10px;
      span {
        font-size: 24px;
        color: #6c5dd3;
      }
    }
  }
}
.content {
  margin-top: 15px;
}
.mylink {
  margin-right: 10px;
  color: $primary;
  a {
    color: $primary;
  }
}
</style>
